import '../public/index'
import request from '../data/request'
import url from '../data/url'
import { toIndex } from '../data/util'
import { header } from '../data/config'
import store from 'store'

import {
  checkKeySn as valid_checkKeySn,
  remark as valid_remark
} from '../data/validate'

const base        = url.base,
      addKeyboard = request.addOrModifyKeyboard,
      storeData   = store.get('storeData')

const title ='POS金属键盘',
  action = '修改';

if (!storeData) {
  layer.msg('数据错误', {
    icon: 5
  })
  
  window.location = './index.html'
}

let form = new Vue({
  el: '#form',
  data: () => { // 设置成函数才可以调用$options.data()方法来清空数据
    return {
      id     : '',
      keySn  : '',
      remark : '',
      isLock : false
    }
  },
  mounted: function() { // 生命周期
    valid()
    // 合并数据
    $.extend(this.$data, storeData)
  }
})

function valid() {

  let form_valid,
      $form = $('#form')
  
  $.validator.setDefaults({ // 只能放在validate规则配置之前

    // 提交事件
    submitHandler: () => {

      // 检测数据是否改变
      if (form.keySn === storeData.keySn && form.remark === storeData.remark) {
        layer.msg('数据未改变', {
          icon: 5
        })

        return
      }
      
      console.log('submit!')

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      form.isLock = true

      $.ajax({
        url: base + addKeyboard,
        type: 'POST',
        contentType: 'application/json',
        headers: header,
        data: JSON.stringify({
          id : form.id,
          keySn: form.keySn,
          remark: form.remark
        })
      })
        .done(function(res) {
          console.log(res)

          if (res.code === -1 ) {
            layer.msg(res.message, {
              icon: 5
            })

            return
          }

          layer.msg(`${action}${ title }成功`, {
            icon: 6
          })

          // 重置表单
          $.extend(form.$data, form.$options.data())

          toIndex()

        })
        .fail(function(res) {
          console.log(res)

          layer.msg(`${action}${ title }失败`, {
            icon: 5
          })

          console.log("error");
        })
        .always(function(res) {

          layer.close(loading_modal)
          form.isLock = false

        })

    }
  })

  // 验证
  form_valid = $form.validate({
    rules: {
      keySn  : valid_checkKeySn,
      remark : valid_remark
    }
  })

}